package com.thingsgrid.auth.support;

import com.thingsgrid.auth.service.BladeUserDetails;
import com.thingsgrid.auth.utils.TokenUtil;
import org.springblade.core.tool.utils.Func;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

/**
 * jwt返回参数增强
 *
 * @author Chill
 */
public class BladeJwtTokenEnhancer implements TokenEnhancer {
	@Override
	public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
		BladeUserDetails principal = (BladeUserDetails) authentication.getUserAuthentication().getPrincipal();
		Map<String, Object> info = new HashMap<>(16);
		info.put(TokenUtil.CLIENT_ID, TokenUtil.getClientIdFromHeader());
		info.put(TokenUtil.USER_ID, Func.toStr(principal.getUserId()));
		info.put(TokenUtil.DEPT_ID, Func.toStr(principal.getDeptId()));
		info.put(TokenUtil.ROLE_ID, Func.toStr(principal.getRoleId()));
		info.put(TokenUtil.TENANT_ID, principal.getTenantId());
		info.put(TokenUtil.ACCOUNT, principal.getAccount());
		info.put(TokenUtil.USER_NAME, principal.getUsername());
		info.put(TokenUtil.NICK_NAME, principal.getName());
		info.put(TokenUtil.ROLE_NAME,principal.getRoleName());
//		if("admin".equals(principal.getAccount())){
//			info.put(TokenUtil.ROLE_NAME,"administrator");
//		}
		info.put(TokenUtil.AVATAR, principal.getAvatar());
		info.put(TokenUtil.LICENSE, TokenUtil.LICENSE_NAME);
		((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
		return accessToken;
	}
}
